import os
import pypyodbc
import requests
import time
import datetime
# import config
import sys
import json
import logging
import threading
logging.basicConfig(filename='logger.log', format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(name=__name__)
# logger.setLevel(level=logging.INFO)
filehandler = logging.FileHandler("log.txt")
filehandler.setLevel(logging.WARNING)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
filehandler.setFormatter(formatter)
console = logging.StreamHandler()  # 日志信息显示在终端terminal
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(filehandler)
logger.addHandler(console)


# path = '//192.168.3.7/zz/20219.mdb'
# 读取基础配置
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(f'{dir_path}/config.json', 'r', encoding='utf-8') as f:
    config = json.load(f)
path = config.get('path')
connStr = 'Driver={Microsoft Access Driver (*.mdb)};DBQ=' + path
time_sleep = config.get('time_sleep')
url = config.get('url')
sql = config.get('sql')


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        """date_time转化方法"""
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        elif isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        else:
            return json.JSONEncoder.default(self, obj)


def get_result(connStr):
    logger.info('开始运行，读取本地文件')
    try:
        conn = pypyodbc.win_connect_mdb(connStr)
    except pypyodbc.Error:
        logger.warning('连接错误')
        return
    cur = conn.cursor()
    # sql = "SELECT * FROM " + 'JieGuo'  # 取表 ActualValues_T
    try:
        cur.execute(sql)
    except pypyodbc.ProgrammingError:
        logger.warning('sql错误')
        return
    # 总序号 扭矩一轴  角度一轴  合格  机型  分序号  日期  操作者  流水号  备注
    alldata = cur.fetchall()
    logger.info(f'data: {alldata}')
    if not alldata:
        logger.warning('没有查询到结果')
    else:
        logger.info('请求客户端')
    return alldata


def analysis(data):
    analysis_result = []
    for i in data:
        try:
            analysis_result.append({
                'main_num': i[0],
                'torque': i[1],
                'angle': i[2],
                'qualified': i[3],
                'type': i[4],
                'num': i[-5],
                'datetime': i[-4],
                'user': i[-3],
                'serial_num': i[-2],
                'note': i[-1],
            })
        except:
            continue
    return analysis_result


def main():
    # 读取数据
    # 读取本地文件
    logger.info('开始运行，读取本地文件')
    result = get_result(connStr)
    # 解析数据
    logger.info('解析文件数据~~~~~~~~~~~~~~~')
    analysis_data = analysis(result)
    # 数据上报
    logger.info('数据上报~~~~~~~~~~~~~~~')
    dict_data = {'data': analysis_data, 'code': 200}
    result_data = json.dumps(dict_data, cls=DateEncoder)
    try:
        response = requests.post(url=url, data=result_data)
    except:
        logger.info('请求未成功')
        return
    response_data = json.loads(response.content)
    logger.info(f'msg: {response_data.get("msg")}  code: {response_data.get("code")}')
    return

